package com.zhuss.advice.processor;

import com.zhuss.advice.db.dao.ext.ProposalDao;
import com.zhuss.bean.bo.advice.proposal.SearchProposalBo;
import com.zhuss.bean.bo.core.upload.DownloadBo;
import com.zhuss.bean.vo.advice.proposal.DetailProposalVo;
import com.zhuss.bean.vo.advice.proposal.ListProposalVo;
import com.zhuss.bean.vo.advice.proposalSon.DetailProposalSonVo;
import com.zhuss.bean.vo.core.upload.DownloadVo;
import com.zhuss.common.PageVo;
import com.zhuss.common.Processor;
import com.zhuss.exception.WpsException;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * @Author: zhushanshuo
 * @Date: 2020/3/6 16:15
 */
@Component("proposalRead")
public class ProposalRead {

    @Autowired
    private ProposalDao proposalDao;

    @Autowired
    private ProposalSonRead proposalSonRead;

    @Autowired
    @Qualifier("downloadProcessor")
    private Processor<DownloadVo, DownloadBo> downloadProcessor;

    /**
     * 用户列表
     * @param bo
     */
    public Object list(SearchProposalBo bo) {
        PageVo<ListProposalVo> result = new PageVo<ListProposalVo>();
        result.setPageNum(bo.getPageNum());
        result.setPageSize(bo.getPageSize());
        if (bo.getCreateTime() != null){
            bo.setCreateTimeStart(DateUtil.toDateOnly(bo.getCreateTime()));
        }
        if (bo.getCreateTime() != null){
            bo.setCreateTimeEnd(DateUtil.toDateOnlyEnd(bo.getCreateTime()));
        }
        result.setItems(proposalDao.list(bo));
        result.setTotal(proposalDao.countList(bo));
        return result;
    }

    /**
     * 详情
     * @throws WpsException
     */
    public Object detail(Long proposalId) throws WpsException {
        DetailProposalVo result = proposalDao.detail(proposalId);
        DownloadBo downloadBo = new DownloadBo();
        downloadBo.setKey(result.getProposalKey());
        DownloadVo downloadVo = downloadProcessor.process(downloadBo);
        result.setProposalUrl(downloadVo.getUrl());
        DetailProposalSonVo proposalSonVo = null;
        try {
            proposalSonVo = (DetailProposalSonVo)proposalSonRead.detail(proposalId);
        } catch (WpsException e) {
            if (ExceptionCode.数据不存在.getCode().intValue() != e.getCode().intValue()) {
                throw e;
            }
        }
        if (proposalSonVo != null){
            result.setProposalSonId(proposalSonVo.getProposalSonId());
            result.setSonContent(proposalSonVo.getSonContent());
            result.setReplyCreator(proposalSonVo.getCreator());
            result.setReplyCreatorId(proposalSonVo.getCreatorId());
            result.setReplyTime(proposalSonVo.getCreateTime());
        }
        if (result == null) {
            throw new WpsException(ExceptionCode.数据不存在);
        }
        return result;
    }
}
